package fun.tan90.easy.binlog.plugin.redis.cluster.service.impl;

import cn.hutool.json.JSONUtil;
import fun.tan90.easy.binlog.plugin.common.service.PluginService;
import fun.tan90.easy.binlog.plugin.redis.cluster.model.RedisClusterParams;
import fun.tan90.easy.binlog.plugin.redis.common.constants.RedisPluginConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.time.Duration;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * description TODO
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2023/11/15 14:41
 */
@Slf4j
public class RedisClusterPluginService implements PluginService {

    @Override
    public boolean test(String params) {
        RedisClusterParams redisClusterParams = JSONUtil.toBean(params, RedisClusterParams.class);
        // 创建连接池配置对象
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMinIdle(redisClusterParams.getMinIdle());   // 设置最小空闲连接数
        poolConfig.setMaxIdle(redisClusterParams.getMaxIdle());   // 设置最大空闲连接数
        poolConfig.setMaxTotal(redisClusterParams.getMaxTotal()); // 设置最大连接数
        poolConfig.setMaxWait(Duration.ofMillis(redisClusterParams.getMaxWait()));   // 设置从连接池获取连接的最大等待时间

        Set<HostAndPort> jedisClusterNodes = redisClusterParams.getNodes().stream().map(n -> new HostAndPort(n.getHost(), n.getPort())).collect(Collectors.toSet());
        int timeout = redisClusterParams.getTimeout();
        int maxAttempts = redisClusterParams.getMaxAttempts();
        int soTimeout = RedisPluginConstants.SO_TIMEOUT;
        String user = StringUtils.hasLength(redisClusterParams.getUser()) ? redisClusterParams.getUser() : null;
        String password = StringUtils.hasLength(redisClusterParams.getPassword()) ? redisClusterParams.getPassword() : null;
        try (JedisCluster jedisCluster = new JedisCluster(jedisClusterNodes, timeout, maxAttempts, soTimeout, user, password, "eb_redis_cluster", poolConfig)) {
            return !CollectionUtils.isEmpty(jedisCluster.getClusterNodes());
        } catch (Exception e) {
            return false;
        }
    }
}
